from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.serialization import pkcs12
import os

def install_cert(cert_path, password=None, cert_store="Root"):
    """
    安装 .p12 证书文件到指定证书存储区。
    
    :param cert_path: .p12 文件路径
    :param password: P12 文件密码，如果无密码传 None
    :param cert_store: 存储区名称，如 "Root"
    """
    with open(cert_path, "rb") as f:
        p12_data = f.read()

    # 加载 P12 文件
    data = pkcs12.load_pkcs12(p12_data, password)
    certificate = data.cert if data.cert else data.additional_certs[0].certificate
    print("cert")
    print(certificate)

    # 将证书导出为 DER 格式
    cert_der = certificate.public_bytes(serialization.Encoding.DER)

    # 创建临时 CER 文件用于 certutil 导入
    temp_cer_path = "temp_cert.cer"
    with open(temp_cer_path, "wb") as f:
        f.write(cert_der)

    # 调用 certutil 安装证书
    os.system(f'certutil -addstore -f "{cert_store}" "{temp_cer_path}"')

if __name__ == "__main__":
    install_cert("mitmproxy-ca-cert.p12", password=None)